package cn.bugstack.springframework.beans.factory.support;

import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.PropertyValue;
import cn.bugstack.springframework.beans.PropertyValues;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import cn.bugstack.springframework.beans.factory.config.BeanReference;
import cn.hutool.core.bean.BeanUtil;

import java.lang.reflect.Constructor;

/**
 * @author oyz
 */
public abstract  class AbstractAutowireCableBeanFactory extends AbstractBeanFactory{


    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean = null;
        try {

            bean = createBeanInstance(beanDefinition,beanName,args);
            // 给该bean填充属性
            applyPropertyValues(beanName,bean,beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed",e);
        }
        // 把该bean放入ioc容器里边
        addSingleton(beanName,bean);
        return bean;
    }

    protected  void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) throws BeansException {
        PropertyValues propertyValues = beanDefinition.getPropertyValues();
        for (PropertyValue pv: propertyValues.getPropertyValues()){
            // 属性名
            String name = pv.getName();
            // 属性值
            Object value = pv.getValue();
            // A依赖于B,获取B的实例化,这里不考虑传递依赖关系
            if (value instanceof BeanReference){
               BeanReference beanReference = (BeanReference) value;
                try {
                    value = getBean(beanReference.getBeanName());
                } catch (BeansException e) {
                    throw new BeansException("Error setting property values："+ beanName);
                }
            }
            // 属性填充
            BeanUtil.setFieldValue(bean,name,value);
        }
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) throws Exception {
        Constructor constructor = null;
        Class beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor:declaredConstructors){
            if(null != args&&ctor.getParameterTypes().length == args.length){
                constructor = ctor;
                break;
            }
        }


        return instantiationStrategy.instantiate(beanDefinition,beanName,constructor,args);
    }


}
